package com.chezhujie.www.controller;

import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.core.shiro.MethodToStaticCache;
import com.chezhujie.www.domain.XyMenu;
import com.chezhujie.www.service.XyMenuService;
import com.chezhujie.www.utils.ConvertObj;
import com.chezhujie.www.utils.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *   菜单栏
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/xymenu")
public class XyMenuController extends BaseController<XyMenu>{
    @Autowired
    private XyMenuService xymenuService;
    @Autowired
    private MethodToStaticCache methodToStaticCache;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, XyMenu xymenu, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xymenu,req,model);
        setParentId(model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            if(xymenu.getParentId()==null||"0".equals(xymenu.getParentId())){
                xymenu.setParentId("0");
            }
            Map<String, Object> params = ConvertObj.toMap(xymenu);
            Pagination pagination = xymenuService.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取菜单栏列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", xymenu);
        return "xymenu/list";
    }
    /**
    * api接口菜单栏列表
    * @param pageNo
    * @param pageSize
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiList.jn")
    public void apiList(Integer pageNo, Integer pageSize, XyMenu xymenu,
        HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(xymenu);
            Pagination pagination = xymenuService.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1,"","",pagination,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取菜单栏列表失败!"+e,"",resp);
        }

    }
    /**
    * api接口菜单栏详情
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiDetail.jn")
    public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
    ModelMap model) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> enumeration = req.getParameterNames();
        if(enumeration.hasMoreElements()){
            String next = enumeration.nextElement();
            params.put(next, req.getParameter(next));
        }

        try {
            Map<String,Object> result = xymenuService.getApiDetail(params);
            jsonResult(1,"","",result,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","获取菜单栏详情失败!"+e,"",resp);
        }

    }
    /** api测试页面 **/
    @RequestMapping("/apiTest.do")
    public String apiList(HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        model.addAttribute("entity",new HashMap<String,Object>());
        return "xymenu/apiTest";

    }

    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(XyMenu xymenu,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(xymenu.getMenuId())){
                if(StringUtils.isBlank(xymenu.getParentId())||"0".equals(xymenu.getParentId())) {
                    xymenu.setParentId("0");//0表示是最顶层
                }
                if(xymenu.getIfMenu()==null||xymenu.getIfMenu()==0){
                    xymenu.setStatus(1);//如果是按钮则没有隐藏这回事
                }
                xymenuService.update(xymenu);


            }else{
                //--------------
                //url 检查数据库是否存在（链接）
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("url", xymenu.getUrl());
                List<Map<String, Object>> list = xymenuService.getList(param);
                if(list.size()>0){
                    model.addAttribute("failed", "菜单链接不能重复");
                    return "redirect:list.do?parentId="+xymenu.getParentId();
                }
                //nameEn 检查数据库是否存在（标识）
                Map<String, Object> param2 = new HashMap<String, Object>();
                param2.put("url", xymenu.getNameEn());
                List<Map<String, Object>> list2 = xymenuService.getList(param2);
                if(list2.size()>0){
                    model.addAttribute("failed", "菜单标识不能重复");
                    return "redirect:list.do?parentId="+xymenu.getParentId();
                }
                //-------------------
                xymenu.setMenuId(UUIDUtils.getUUID());
                if(StringUtils.isBlank(xymenu.getParentId())||"0".equals(xymenu.getParentId())){
                    xymenu.setParentId("0");//0表示是最顶层
                }else{
                    XyMenu vo = xymenuService.queryById(xymenu.getParentId());
                    vo.setHasMenu(1);
                    xymenuService.update(vo);
                }
                if(xymenu.getOrderBy()==null){
                    xymenu.setOrderBy(99);
                }
                if(xymenu.getIfMenu()==null||xymenu.getIfMenu()==0){
                    xymenu.setStatus(1);//如果是按钮则没有隐藏这回事
                }
                xymenuService.insert(xymenu);
            }
            model.addAttribute("success", "保存菜单栏成功");
            methodToStaticCache.addCache();
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存菜单栏失败!详情："+e.getMessage());
        }

        return "redirect:list.do?parentId="+xymenu.getParentId();
    }


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String menuId,XyMenu xymenu, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xymenu,req,model);
        setParentId(model);
        try {
            XyMenu entity = xymenuService.queryById(xymenu.getMenuId());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询菜单栏出错!详情："+e.getMessage());
        }
        return "xymenu/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(XyMenu xymenu, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(xymenu,req,model);
        setParentId(model);
        if(StringUtils.isNotBlank(xymenu.getMenuId())){
            xymenu = xymenuService.queryById(xymenu.getMenuId());
            model.addAttribute("entity", xymenu);
        }
        return "xymenu/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String menuId,XyMenu xymenu, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            xymenuService.deleteById(xymenu.getMenuId());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setParentId(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listParentId = xymenuService.getListParentId(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("listParentId", listParentId);
    }

    private void setMsg(XyMenu xymenu,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", xymenu);
    }
}
